import {
  queryAllHotelTheme,
  queryBedAndBreakfast
} from '@/api/theme-hotel'

const getDefaultState = () => {
  return {
    theme: [],
    hotel: [],
    bed: [],
    breakfast: [],
    htmlCache: ''
  }
}

const state = { ...getDefaultState() }

const mutations = {
  INIT: (state) => {
    state = { ...getDefaultState() }
  },
  SET_THEME: (state, theme) => {
    state.theme = theme
  },
  SET_HOTEL: (state, hotel) => {
    state.hotel = hotel
  },
  SET_BED: (state, bed) => {
    state.bed = bed
  },
  SET_BREAKFAST: (state, breakfast) => {
    state.breakfast = breakfast
  },
  SET_HTML_CACHE: (state, html) => {
    state.htmlCache = html
  },
  EMPTY_HTML_CACHE: (state) => {
    state.htmlCache = ''
  }
}

const actions = {
  init({ commit }) {
    commit('INIT')
  },
  setTheme({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.theme.length) {
        resolve(state.theme)
      }
      queryAllHotelTheme().then(res => {
        commit('SET_THEME', res.data)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setHotel({ commit }, hotel) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_HOTEL', hotel)
        resolve(hotel)
      } catch (error) {
        reject(error)
      }
    })
  },
  setEmptyHotel({ commit }) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_HOTEL', [])
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  },
  setBedAndBreakfast({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.bed.length && state.breakfast.length) {
        resolve({
          bed: state.bed,
          breakfast: state.breakfast
        })
        return
      }
      queryBedAndBreakfast().then(res => {
        commit('SET_BED', res.data.bed)
        commit('SET_BREAKFAST', res.data.breakfast)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setHtmlCache({ commit }, html) {
    if (html) {
      commit('SET_HTML_CACHE', html)
    } else {
      commit('EMPTY_HTML_CACHE')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

